import {createRouter, createWebHistory} from 'vue-router'
import User from '../views/User.vue'
import Login from '../views/Login'
import Layout from "../layout/Layout";
import Register from '../views/Register';
import Person from '../views/Person'
import Home from "../views/Home";

const routes = [
    {
        path: '/', component: Layout,
        /*重定向实现路由跳转*/
        redirect:'/home',
        children: [
            {path:'/home',component:Home},
            {path:'/user',component:User},
            {path: '/person',component: Person},
            {path: '/book',component: ()=>import('@/views/Book')},
            {path: '/news',component: ()=>import('@/views/News')},
            {path: '/travel',component: ()=>import('@/views/Travel')}
        ]
    },
    {path: '/login', component: Login},
    {path: '/register',component: Register}
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

/*定义路由导航守卫
* /*
   定义路由导航守卫
   to: 路由跳转的网址
   from: 路由从哪里来
   next: 是一个函数，表示放行或重定向
         next() 放行
         next("/login")重定向
   业务逻辑:
        如果访问login页面，直接放行
        如果不是访问login页面，检查是否有token

 */
router.beforeEach((to,from,next)=>{
    if(to.path === "/login"||to.path==='/register'){
        return next()
    }
    let token=window.sessionStorage.getItem("token")
    //if(token !==null && token.length>0)
    //下列if的判断，解释为：如果token不为null，用于字符串的判断
    if(token){
        return next()
    }
    next("/login")
})


export default router
